package org.smile.pager.easyui;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.smile.db.PageModel;
import org.smile.json.JSONObject;
import org.smile.pager.Pager;

public class EasyuiPager implements Pager{
	
	protected static final Logger logger=Logger.getLogger(EasyuiPager.class);
	/**
	 * 每页显示条数
	 */
	private int size=15;
	/**
	 * 当前页
	 */
	private int page=1;
	
	private HttpServletResponse response=null;
	
	private HttpServletRequest request=null;
	
	public EasyuiPager(HttpServletRequest request,HttpServletResponse response){
		this.request=request;
		this.response=response;
		refreshPage();
	}
	public EasyuiPager(HttpServletRequest request,HttpServletResponse response,int size){
		this.request=request;
		this.response=response;
		this.size=size;
		refreshPage();
	}
	/**
	 * 
	 */
	public void refreshPage() {
		try{
			String pageStr=request.getParameter("page");
			if(pageStr!=null&&!"".equals(pageStr)){
				this.page=Integer.parseInt(pageStr);
			}
			String crd=request.getParameter("rows");
			if(crd!=null&&!"".equals(crd)){
				size=Integer.parseInt(crd);
			}
		}catch(Exception e){
			logger.error("获取分布参数出错", e);
		}
	}
	public void commitResult(PageModel pageModel) {
		
		String chartSet=request.getCharacterEncoding();
		
		if(chartSet!=null){
			response.setCharacterEncoding(chartSet);
		}
		try {
			PrintWriter pw=response.getWriter();
			pw.print(JSONObject.toJSONString(pageModel));
			
		} catch (IOException e) {
			logger.error("读取servlet数据流出错", e);
		}
	}
	
	public int getPage() {
		return page;
	}
	
	public HttpServletRequest getRequest() {
		return request;
	}
	
	public int getSize() {
		return size;
	}
	
	public Map getParameterMap() {
		return request.getParameterMap();
	}

}
